import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'index.dart';
import 'widgets/index.dart';
import '../../common/values/images.dart';
import '../../common/routers/names.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});
  
  static final PageController _pageController = PageController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 2,
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            // 左侧位置图标和地址（动态显示定位信息）
            GestureDetector(
              onTap: () async {
                // 🎯 跳转到地图页面并等待用户选择位置
                final result = await Get.toNamed(RouteNames.systemMap);
                
                // 🎯 如果用户选择了位置，更新首页位置信息
                if (result != null && result is Map<String, dynamic>) {
                  controller.updateLocationFromMap(result);
                }
              },
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 定位图标（加载时显示动画）
                  Obx(() => controller.isLocationLoading.value
                      ? const SizedBox(
                          width: 28,
                          height: 28,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF333333)),
                          ),
                        )
                      : Image.asset(
                          AssetsImages.locationPng,
                          width: 28,
                          height: 28,
                          color: const Color(0xFF333333),
                        ),
                  ),
                  const SizedBox(width: 6),
                  // 动态位置信息显示
                  Container(
                    constraints: const BoxConstraints(maxWidth: 180),
                    child: Obx(() => Text(
                      // 🎯 当使用默认位置时显示"未定位"，否则显示实际位置
                      controller.isDefaultLocation.value ? "未定位" : controller.locationInfo.value,
                      style: TextStyle(
                        color: controller.isLocationLoading.value 
                            ? const Color(0xFF999999) 
                            : (controller.isDefaultLocation.value 
                                ? const Color(0xFF999999)  // 未定位时使用灰色
                                : const Color(0xFF333333)), // 有定位时使用黑色
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    )),
                  ),
                ],
              ),
            ),
            const Spacer(),
            // 刷新按钮
            Obx(() => GestureDetector(
              onTap: controller.isLoadingNearby.value ? null : controller.onRefresh,
              child: Container(
                padding: const EdgeInsets.all(4),
                child: controller.isLoadingNearby.value
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF333333)),
                        ),
                      )
                    : const Icon(
                        Icons.refresh,
                        size: 28,
                        color: Color(0xFF333333),
                      ),
              ),
            )),
            const SizedBox(width: 12),
            // 右侧消息图标（带小黄点通知）
            GestureDetector(
              onTap: () {
                // 🔥 点击消息图标时清除通知状态
                controller.clearMessageNotification();
                Get.toNamed(RouteNames.messageMessageIndex);
              },
              child: Stack(
                children: [
                  // 消息图标
                  Image.asset(
                    AssetsImages.msgPng,
                    width: 28,  
                    height: 28,
                    color: const Color(0xFF333333),
                  ),
                  // 🔥 小黄点通知（当有好友申请消息时显示，符合MyApplication2逻辑）
                  Obx(() => controller.hasUnreadMessage.value
                      ? Positioned(
                          right: 0,
                          top: 0,
                          child: Container(
                            width: 10,
                            height: 10,
                            decoration: const BoxDecoration(
                              color: Color(0xFFFFD700), // 🔥 修复：改为黄色小点，符合MyApplication2
                              shape: BoxShape.circle,
                            ),
                          ),
                        )
                      : const SizedBox.shrink()),
                ],
              ),
            ),
          ],
        ),
      ),
      body: Obx(() {
        if (controller.state.isLoadingWaterfall.value) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        
        if (controller.state.waterfallItems.isEmpty) {
          return const Center(
            child: Text('暂无数据'),
          );
        }
        
        return Stack(
          children: [
            // 主要的PageView内容
            GestureDetector(
              onPanStart: (details) {
                controller.onPullStart();
              },
              onPanUpdate: (details) {
                // 只有向下滑动且在第一页时才处理
                if (details.delta.dy > 0 && controller.currentPageIndex.value == 0) {
                  controller.onPullUpdate(details.delta.dy);
                }
              },
              onPanEnd: (details) {
                controller.onPullEnd();
              },
              child: PageView.builder(
                controller: _pageController,
                scrollDirection: Axis.vertical,
                itemCount: controller.state.waterfallItems.length,
                physics: const BouncingScrollPhysics(),
                onPageChanged: (index) {
                  // 更新当前页面索引
                  controller.updateCurrentPageIndex(index);
                  
                  // 打印页面切换信息
                  // debugPrint('📱 页面切换事件:');
                  // debugPrint('   当前页面索引: $index');
                  // debugPrint('   总页面数: ${controller.state.waterfallItems.length}');
                  // if (index < controller.state.waterfallItems.length) {
                  //   final item = controller.state.waterfallItems[index];
                  //   debugPrint('   当前卡片ID: ${item.id}');
                  //   debugPrint('   图片数量: ${item.imageUrls.length}');
                  //   debugPrint('   作者: ${item.authorName}');
                  // }
                  // debugPrint('   ═════════════════════════════');
                },
                itemBuilder: (context, index) {
                  final item = controller.state.waterfallItems[index];
                  return WaterfallItemCard(
                    key: ValueKey(item.id), // 性能优化：使用唯一key
                    item: item,
                    onNext: () {
                      // X按钮点击切换下一个数据项
                      final nextIndex = index + 1;
                      if (nextIndex < controller.state.waterfallItems.length) {
                        _pageController.animateToPage(
                          nextIndex,
                          duration: const Duration(milliseconds: 300),
                          curve: Curves.easeInOut,
                        );
                      }
                    },
                  );
                },
              ),
            ),
            
            // 下拉刷新指示器
            Obx(() => AnimatedPositioned(
              duration: const Duration(milliseconds: 200),
              top: controller.isPullingDown.value 
                  ? controller.pullDownOffset.value - 60 
                  : -60,
              left: 0,
              right: 0,
              child: Container(
                height: 60,
                alignment: Alignment.center,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                  decoration: BoxDecoration(
                    color: controller.canTriggerRefresh.value 
                        ? const Color(0xFF4CAF50) 
                        : Colors.white.withOpacity(0.9),
                    borderRadius: BorderRadius.circular(20),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 10,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 刷新图标或加载动画
                      controller.isLoadingNearby.value
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            )
                          : Icon(
                              controller.canTriggerRefresh.value 
                                  ? Icons.refresh 
                                  : Icons.arrow_downward,
                              color: controller.canTriggerRefresh.value 
                                  ? Colors.white 
                                  : const Color(0xFF666666),
                              size: 20,
                            ),
                      const SizedBox(width: 8),
                      // 提示文字
                      Text(
                        controller.isLoadingNearby.value
                            ? '正在刷新...'
                            : controller.canTriggerRefresh.value
                                ? '松手刷新'
                                : '下拉刷新',
                        style: TextStyle(
                          color: controller.canTriggerRefresh.value 
                              ? Colors.white 
                              : const Color(0xFF666666),
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )),
          ],
        );
      }),
    );
  }

}